import { ref } from 'vue'
import { defineStore } from 'pinia'

import { reqLonin, reqInfo, reqLonOut } from '@/api/user'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import type { loginForm } from '@/api/user/type'
import { constantRoute, asyncRoute, anyRoutes } from '@/router/router'

import cloneDeep from 'lodash/cloneDeep'
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
export const useCounterStore = defineStore('counter', () => {
  const token = ref(sessionStorage.getItem('token'))
  const menuRoute = ref<RouteRecordRaw[]>(constantRoute)
  const buttons = ref<any[]>([])
  const getInfo = ref()
  // 获取用户信息
  const userReqInfo = async () => {
    const res: any = await reqInfo()
    if (res.code == 200) {
      getInfo.value = res
      buttons.value = res.data.buttons
      const useAsyncRoute = filterAsyncRoute(
        cloneDeep(asyncRoute),
        res.data.routes,
      )
      menuRoute.value = [...constantRoute, ...useAsyncRoute]
      let a = [...useAsyncRoute, asyncRoute, ...anyRoutes].forEach(
        (item: any) => {
          router.addRoute(item)
        },
      )
      return 'ok'
    } else {
      return Promise.reject(new Error(res.code.toString()))
    }
  }
  // 退出登录
  const userLogOut = async () => {
    getInfo.value = ref().value
    token.value = ''
    sessionStorage.removeItem('token')
    await reqLonOut()
  }
  // 登录
  const userLogin = async (data: loginForm) => {
    const res: any = await reqLonin(data)
    if (res.code == 200) {
      token.value = res.data as string
      sessionStorage.setItem('token', token.value)
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }

  return {
    token,
    userLogin,
    menuRoute,
    userReqInfo,
    getInfo,
    userLogOut,
    buttons,
  }
})
